package com.xiaoma.guava;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.Weigher;
import java.util.concurrent.TimeUnit;
import org.junit.Test;

public class CacheBuilderDemo {

  @Test
  public void cache() throws InterruptedException {

    Cache<String, String> keyCache = CacheBuilder.newBuilder()
            //最大容量
        .maximumSize(1000)
            //过期时间
        .expireAfterWrite(11, TimeUnit.MILLISECONDS)

        .maximumWeight(1024 * 1024*3)
        // 设置用来计算缓存容量的Weigher
       .weigher(new Weigher<String, String>() {
          @Override
          public int weigh(String key, String value) {
            return key.getBytes().length + value.getBytes().length;
          }

        })


            .build();


        Thread thread = new Thread(() -> {
            for (int i=0;i<2000;i++){
              keyCache.put("aa"+i, "11");
            }
        });
        thread.start();

        Thread.sleep(10000);

      System.out.println(keyCache.size());

/*
        while (true){
            System.out.println(keyCache.size());
        }
*/

//    System.out.println(keyCache.getIfPresent("aa"));

  }

}
